﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RedisBitMapDemo
{
    public class UserSignCase
    {
        public void Run()
        {
            var connString = "localhost:6379,defaultDatabase=0,connectTimeout=3000";
            var conn = ConnectionMultiplexer.Connect(connString);
            var db = conn.GetDatabase(0);

            // 用户签到场景 一个月签到数据 
            // key: SIGN:{userId}{year}{month}
            // 是否签到：0/1
            // DateTime.Today: 2022-01-31

            // 当日（2022-01-31）签到
            // setbit SIGN:10001_202201 0 1
            // ret = false ,返回之前的数据
            var ret = db.StringSetBit("SIGN:10001_202201", 30, true);

            // 获取当日是否签到
            // getbit SIGN:10001_202201 0
            // signed = true
            var signed = db.StringGetBit("SIGN:10001_202201", 30);

            // 获取本月首次签到数据
            // bitpos SIGN:10001_202201 0
            // day = 30
            var day = db.StringBitPosition("SIGN:10001_202201", true, 0);

            // 获取本月签到天数
            // bitcount SIGN:10001_202201 0 30
            // days = 1
            var days = db.StringBitCount("SIGN:10001_202201", 0, 30);

            // 获取本月签到明细
            var val = (byte[])db.StringGet("SIGN:10001_202201");

            // 转二进制数组
            var binarySb = new StringBuilder();
            for (int i = 0; i < val.Length; i++)
            {
                binarySb.Append(Convert.ToString(val[i], 2).PadLeft(8, '0'));
            }

            // binarySb = {00000000000000000000000000000010}
            var binaryIntArray = binarySb.ToString().ToCharArray().Select(o => o == '1' ? 1 : 0).ToArray();
        }

    }
}
